#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import logging
import wsgiref.handlers
from apptwitter import AppEngineTwitter
from django.utils import simplejson
from google.appengine.ext import webapp
from google.appengine.api import xmpp
from google.appengine.ext import db
from db_service import DBService
import xml.sax.saxutils
import config

OAUTH_KEY = config.OAUTH_KEY
OAUTH_SECRET = config.OAUTH_SECRET
BOT=config.ACCOUNT

HEADER='''
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>TwiTalker - Tweet it Easy with your Gtalk</title>
<link href="/img/favicon.ico" rel="shortcut icon" type="image/x-icon">
<link rel="stylesheet" type="text/css" media="screen" href="/css/style.css" /> 
</head>

<body>
<div id="top"></div>
<div id="header">
<div id="header_box"><img style="float:left" src="img/logo.png" />
<ul id="navCircle">
<!-- CSS Tabs -->
<li><a href="/">Home</a></li>
<li><a href="faq">FAQ</a></li>
<li><a href="http://twitalkerblog.appspot.com">BLOG</a></li>
</ul>
</div>
<div class="clean"></div>
</div>
<div id="header_bottom"></div>
'''

JS='''
<SCRIPT LANGUAGE="JavaScript">
<!-- Begin
function copyit(theField) {
var tempval=eval("document."+theField)
tempval.focus()
tempval.select()
therange=tempval.createTextRange()
therange.execCommand("Copy")
}
//  End -->
</script>
'''

FOOTER='''
<div id="footer">
Copyright (C) 2009-2010 TwiTalker | <a href="http://www.kavingray.com">Kavin</a> |
<a href="http://code.google.com/p/twitalker/">Open Source</a> |
Powered by <a href="http://code.google.com/appengine/">Google appengine</a>
</div>
</body>
</html>
'''

 
 
class InitHandler(webapp.RequestHandler):
 
    def get(self):
      
        twitter = AppEngineTwitter()
        twitter.set_oauth(key=OAUTH_KEY, secret=OAUTH_SECRET)
        req_info = twitter.prepare_oauth_login()
        
        OAuthRequestToken(token=req_info['oauth_token'],
                          secret=req_info['oauth_token_secret']).put()
        
        # get the oauth url
        oauth_url=xml.sax.saxutils.escape(req_info['url'], {'"': "&quot;"})
        # oauth_url=h(req_info['url'])


        content='''
        <div id="container">
        <div id="intro"><h2>Tweet  It  Easy</h2>
        <p>TwiTalker is a powerful Twitter robot based on Google Talk.To sign up and use TwiTalker,
        click the <a href="%s">login in with Twitter</a> Button on the right in order to verify and bind to your account.
        <a href="faq">( How to verify? )</a>.Go to FAQ page if you need help and follow<a href="http://twitter.com/Twi_Talker">@Twi_Talker</a>
        to get notifications about updates and changes to TwiTalker. <br /></p>

        <h2>Commands: </h2>
        <p>Get help and command list: -help</p>
        <p>Bind to account: -v AccessKey AccessSecret</p>
        <p>Remove binding: -remove</p>
        <p>Set on-mode (receive tweets and DM from your friends): -on</p>
        <p>Set self-mode (only received mentioned tweets and DM)：-self</p>
        <p>Set off-mode(never receive tweets)：-off</p>
        <p>Retrieve latest mentioned tweets: -@</p>
        <p>Retrieve latest direct message: -d</p>
        <p><a href="faq">Go to FAQ page to get more commands....</a></p>
        </div>

        <div id="step">
        <h2>OAuth</h2>
        <a href="%s"><img style="margin-bottom:0px" src="img/login.png" /></a><br />
        <h2>About TwiTalker</h2>
        <p>TwiTalker is developed by <a href="http://www.kavingray.com">Kavin</a> (Follow <a href="http://twitter.com/kavin_gray">Kavin</a> on twitter).
        It's Powered by Google app engine platforms.This service provides a different and easy way for you to use Twitter.
        You can send tweet and receive friends' updates directly in Gtalk without login in your Twitter account.</p>
        <img style="margin-bottom:0px" src="img/tie.png" />
        </div>
        <div class="clean"></div>
        </div>
        '''%(oauth_url,oauth_url)
    
        # initing the pages    
        self.response.out.write(HEADER)    
        self.response.out.write(content)
        self.response.out.write(FOOTER)


 
class FaqHandler(webapp.RequestHandler):
 
    def get(self):
      
        content='''
        <div id="container">
        <div id="content">
        <h2>FAQ</h2>
        <p>
        <a href="#Q1">How to start using TwiTalker ?</a><br />
        <a href="#Q2">How do I control my Twitter ?</a><br />
        <a href="#Q3">What is self-mode ?</a><br />
        <a href="#Q4">What is live-mode ?</a><br />
        <a href="#Q5">What is id-mode ?</a><br />
        <a href="#Q6">How do I retweet or add tweet to my favorites ?</a><br />
        <a href="#Q7">How do I reply a priticular tweet ?</a><br />
        <a href="#Q8">What is Oauth ? Should I give my twitter passwords ?</a><br />
        <a href="#Q9">How do I remove TwiTalker ?</a><br />
        <a href="#other">More questions ?</a><br />
        </p>
        <h2><a name="Q1">How to start using TwiTalker ?</a></h2>
        <p>First,you need a Twitter account and a Google Talk(GTalk) account.Then verify and bind to your account.There are three steps to finish the binding：<br />
        Step one: Click the button to login in with Twitter and allow TwiTalker access your account.Get your Access Key and Access Secret <br />
        <img src="img/s1.jpg" /><br /><br />
        <img src="img/s2.jpg" /><br /><br />
        Step Two: Add the robot account that you have been recommended to your contact list on GTalk<br />
        <img src="img/s3.jpg" /><br /><br />
        Step Three: Send your binding command<b>(correct formats:-v AccessKey AccessSecret)</b> to the robot in order to connect with your GTalk account.\
        If there is no response from the robot.Please doublecheck your binding command and sent it again.<br />
        <img src="img/s4.jpg" /><br /><br />
        Now you can start using TwiTalker.Type "-help" to get help.
        </p>

        <h2><a name="Q2">How do I control my Twitter ?</a></h2>
        <p>To updates your timeline in Twitter,just type your message to TwiTalker.Besides,TwiTalker provides several commands to control your Twitter:<br />
        Post a tweet: Just type the message and send (less than 140 characters)<br />
        Get help and command list: <b>-help</b><br />
        List all commands: <b>-all</b>
        Bind to account: <b>-v AccessKey AccessSecret</b><br />
        Remove binding: <b>-remove</b><br />
        Get status of your account: <b>-status</b> or <b>-st</b><br />
        Get useful tools: <b>-tool</b><br />
        Set on-mode (receive tweets and DM from your friends): <b>-on</b><br />
        Set self-mode (only received mentioned tweets and DM)：<b>-self</b><br />
        Set live-mode(receive tweets from the default list): <b>-live</b><br />
        Set default list：<b>-live owner list</b> (eg:-live kavin_gray test)<br />
        Set off-mode(never receive tweets)：<b>-off</b><br />
        Set refresh rate.Should be set 1 to 5 mins(1 & 5 included): <b>-time minutes</b><br />
        Retrieve favorites: <b>-fav</b> or <b>-fav page(optional)</b> (Be sure to add 'p' before the page num.eg:-fav p2)<br />
        Retrieve direct messages: <b>-d</b> or <b>-d page(optional)</b> (Be sure to add 'p' before the page num.eg:-d p2)<br />
        Retrieve mentioned tweets: <b>-@</b> or <b>-@ page(optional)</b> (Be sure to add 'p' before the page num.eg:-@ p2)<br />
        Retrieve Retweets by friends:<b>-rt</b> or <b>-rt page(optional)</b> (Be sure to add 'p' before the page num.eg:-rt p2)<br />
        Retrieve tweets of you: <b>-me</b> or <b>-me page(optional)</b> (Be sure to add 'p' before the page num.eg:-me p2)<br />
        Retrieve tweets fome home timeline：<b>-home</b> or <b>-ho</b> or <b>-ho page(optional)</b> (Be sure to add 'p' before the page num.eg:-ho p2)<br />
        Retrieve tweets fome user timeline: <b>-tl username</b> or <b>-tl username page(optional)</b> (Be sure to add 'p' before the page num.eg:-tl kavin_gray p2)<br />
        Search tweets: <b>-s keyword page(optional)</b> (Be sure to add 'p' before the page num.eg:-s twitalker p2)<br />
        Retrieve tweets from list：<b>-list owner list page(optional)</b> or <b>-lt owner list page</b> (Be sure to add 'p' before the page num.eg:-lt twi_talker test p2)<br />
        Retrieve tweets from lists you create：<b>-mlist next/pre</b> or <b>-mt next/pre</b> (next and pre is optional.eg:*-mt next* get next page)<br />
        Retrieve tweets from lists you follow：<b>-list next/pre</b> or <b>-lt next/pre</b> (next and pre is optional.eg:*-lt pre* get previous page)<br />
        Retrieve tweets from lists following you: <b>-listed next/pre</b> or <b>-ld next/pre</b> (next and pre is optional.eg:*-ld pre* get previous page)<br />
        Reply a priticular tweet: <b>-@ id content</b><br />
        Get tweet conversations: <b>-msg id</b><br />
        Delete your latest update: <b>-del</b><br />
        Delete an update: <b>-del id</b><br />
        Send a direct message: <b>-d username content</b><br />
        Add a tweet to favorites: <b>-fav id</b><br />
        Delete favorites: <b>-unfav id</b><br />
        Retweet a tweet(Old Style): <b>-rt id</b> or <b>-rt id content</b><br />
        Retweet a tweet(Offical Style): <b>-r id</b><br />
        Retrieve status about someone: <b>-status username</b> or <b>-st username</b><br />
        Follow someone: <b>-follow username</b> or <b>-fo username</b><br />
        Unfollow someone: <b>-unfollow username</b> or <b>-uf username</b><br />
        Block someone: <b>-block username</b><br />
        If some following you: <b>-if username</b><br />
        id-mode on(attach an id to each tweet):<b>-idon</b><br />
        id-mode off(never attach an id to each tweet):<b>-idoff</b><br />
        Get list of multiple accounts: <b>-bind</b><br />
        Add another account: <b>-bind AccessKey AccessSecret</b><br />
        Delete account binding: <b>-unbind username</b><br />
        Switch account: <b>-switch username</b> or <b>-sw username</b><br />
        </p>

        <h2><a name="Q3">What is self-mode ?</a></h2>
        <p>If you followed too much people and the sea of tweets disturbed you.You can turn on the self-mode.
        It's a notification filter mode which makes you only receive mentioned tweets and direct messages.</p>

        <h2><a name="Q4">What is live-mode ?</a></h2>
        <p>You can receive tweets from the default list by setting the live mode.
        To use live mode,you got to set the default list with the following format for the first time:
        <b>-live owner list</b>.(eg. -live twi_taker test)</p>

        <h2><a name="Q5">What is id-mode ?</a></h2>
        <p>While you set id-mode on.An message id will be attached to each tweets you have recieved.  
        With these message id you can reply or rt tweets</p>


        <h2><a name="Q6">How do I retweet or add tweet to my favorites ?</a></h2>
        <p>Set id-mode on.Each tweet will show up with a message id,like [id: 000001] appended.
        Just type "-r 000001" to retweet it.Type "-fav 000001" to add this tweet into your favorites.</p>

        <h2><a name="Q7">How do I reply a priticular tweet ?</a></h2>
        <p>Simply type <b>@username content</b> to reply someone.If you want to reply a priticular tweet.You can get the tweet's id which you want to reply and tweet it with the following commands: <b>-@ id content</b>.
        If you want to check out the tweets which the target tweet in reply to.Just type <b>-msg id</b> and it will show you a grasp of the conversation before the target tweet.
        <a href="http://www.mobypicture.com/user/kavin_gray/view/5868950">(Still dont get it?)</a></p>


        <h2><a name="Q8">What is Oauth ? Should I give my twitter passwords ?</a></h2>
        <p>OAuth is an authentication protocol that allows users to approve application to act on their behalf without sharing their password.
        TwiTalker use Oauth to connect your account,therefore password is not required to control your Twitter account using</p>

        <h2><a name="Q9">How do I remove TwiTalker ?</a></h2>
        <p>Just type "-remove" to the TwiTalker robot and delete the TwiTalker contact from your contact list.</p>

        <h2><a name="other" id"other">More questions ?</a></h2>
        <p>Post your problem to <a href="http://twitter.com/twi_talker">@Twi_Talker</a> or contact the developer <a href="http://twitter.com/kavin_gray">Kavin</a></p>

        </div>
        </div>'''
    
        self.response.out.write(HEADER)    
        self.response.out.write(content)
        self.response.out.write(FOOTER)



    
      
    

        
        
class CallbackHandler(webapp.RequestHandler):
 
    def get(self):
        
        twitter = AppEngineTwitter()
        twitter.set_oauth(OAUTH_KEY, OAUTH_SECRET)
        req_token = self.request.get('oauth_token')
 
        query = OAuthRequestToken.all()
        query.filter('token = ', req_token)
        req_tokens = query.fetch(1)
 
        acc_token = twitter.exchange_oauth_tokens(req_token, req_tokens[0].secret)
 
        if (twitter.verify()==200):
            name = simplejson.loads(twitter.last_response.content)['screen_name']
            self.response.out.write(HEADER)
            self.response.out.write(JS)
            con_begin='''
            <div id="container">
            <div id="content">
            <h2>Congratulation!</h2>
            <P>Dear %s,you have got the Access Key and Access Secret.<strong>Please do keep them safely </strong>and finish the binding by the following steps:</p>'''%(name.encode("utf-8"))
            self.response.out.write(con_begin)
            self.response.out.write("Access Key:")
            self.response.out.write(acc_token['oauth_token'])
            self.response.out.write("<br />Access Secret: ")
            self.response.out.write(acc_token['oauth_token_secret'])
            con_copy='''
            <form name="it">
            <textarea name="select1" rows="2" cols="120">-v '''+acc_token['oauth_token']+" "+acc_token['oauth_token_secret']+'''</textarea>
            <input onclick="copyit('it.select1')" type="button" value="Copy" name="cpy"></input>
            </form>
            '''
            self.response.out.write(con_copy)
            db_ser = DBService()            
            db_ser.setQuery('TwiCount')
            twiNum=db_ser.getQuery()
            num=twiNum.count()
            if(num<250):
                con_foot='<p>Next Step: Add <b>'+ BOT +'</b> to your contact lists on GTalk\
sending the following command to the TwiTalker robot<br /><b>-v AccessKey AccessSecret</b>(Or just copy the verify infomation in the textarea and send it directly to the TwiTalker robot)'+'</p>'
            else:
                con_foot='<p>There is no TwiTalker robot available now.</p> '
        
            self.response.out.write(con_foot)
            self.response.out.write('<p>Visit <a href="faq">FAQ</a> if you need more help</p>')
            
            self.response.out.write(FOOTER)



    
#Model(s)
 
class OAuthRequestToken(db.Model):
    token = db.StringProperty()
    secret = db.StringProperty() 
 
 
 
logging.getLogger()
routing = [('/', InitHandler),
           ('/faq', FaqHandler),
           ('/oauth', CallbackHandler)]
application = webapp.WSGIApplication(routing, debug=False)
wsgiref.handlers.CGIHandler().run(application)
